﻿using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web;
using OCBizAPI.Models;


namespace OCBizAPI.Controllers
{
    /// <summary>
    /// This sample controller reads the contents of an HTML file upload asynchronously and writes one or more body parts to a local file.
    /// </summary>
    public class FileUploadController : ApiController
    {
        private static string serverPath() {
            return HttpContext.Current.Server.MapPath("~/Uploads/");
        }

        [HttpPost]
        public FileResult UploadFile()
        {
            // Verify that this is an HTML Form file upload request
            if (!Request.Content.IsMimeMultipartContent("form-data"))
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
            }

            // Create a stream provider for setting up output streams
            CustomMultipartFormDataStreamProvider streamProvider = new CustomMultipartFormDataStreamProvider(serverPath());

            // Read the MIME multipart asynchronously content using the stream provider we just created.
            Request.Content.ReadAsMultipartAsync(streamProvider);


            // Create response
            return new OCBizAPI.Models.FileResult
            {
                FileNames = streamProvider.FileData.Select(entry => entry.LocalFileName),
                Submitter = streamProvider.FormData["submitter"]
            };
        }
    }
    public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider {
        public CustomMultipartFormDataStreamProvider(string path)
            : base(path) { }

        public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers) {
            var name = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? headers.ContentDisposition.FileName : "NoName";
            return name.Replace("\"", string.Empty); //this is here because Chrome submits files in quotation marks which get treated as part of the filename and get escaped
        }
    }
}
